package com.jtpay.ysfproductionprocess.utils;

import android.annotation.SuppressLint;
import android.os.Environment;
import android.text.TextUtils;

import com.jtpay.ysfproductionprocess.BuildConfig;

import java.io.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import static com.jtpay.ysfproductionprocess.utils.PayContext.IMG_DIR_NAME;
import static com.jtpay.ysfproductionprocess.utils.PayContext.LOG_DELETE_DAYS;
import static com.jtpay.ysfproductionprocess.utils.PayContext.LOG_DIR_NAME;

/**
 * Created by Joe on 2017/09/11 15:02.
 */

public class PayFileUtil {
    private static final String FILE_EXTENSION_SEPARATOR = ".";
    public static final String FILE_LOG_FIRST_NAME = "log_";
    public static final String TEMP_FILE_LOG_FIRST_NAME = "temp_";
    public static final String FILE_PREFIX = ".log";
    private static final ThreadLocal<SimpleDateFormat> S_DATE_FORMAT = new ThreadLocal<SimpleDateFormat>() {
        @SuppressLint("SimpleDateFormat")
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd");
        }
    };
    public static final String IMG_DIR_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() +
            File.separator + BuildConfig.APPLICATION_ID + File.separator + IMG_DIR_NAME;

    public static final String HEADER_DATE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() +
            File.separator + "yunshanfu" + File.separator + "head.txt";

    private static final String STORAGE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() +
            File.separator + BuildConfig.APPLICATION_ID;

    /**
     * @param message content
     */
    public static void saveLogFile(String message) {
        message = stringNowTime() + " " + message + "\n";
        String fileName = getCurLogFileName();
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            String path = getTargetLogFileDirPath();
            String newFileStr = path + File.separator + fileName;
            FileWriter fileWriter = null;
            try {
                if (!isFileExist(newFileStr)) {
                    File newFile = new File(newFileStr);
                    createDir(newFile.getParent());
                    newFile.createNewFile();
//                    deleteOldFile(LOG_DELETE_DAYS, path);
                }
                File file = new File(path, fileName);
                fileWriter = new FileWriter(file, true);
                fileWriter.write(message);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                quietClose(fileWriter);
            }
        }
    }

    public static String getCurLogFileName() {
        return FILE_LOG_FIRST_NAME + getNowDate() + FILE_PREFIX;
    }

    public static String gettempCurLogFileName() {
        return TEMP_FILE_LOG_FIRST_NAME + getNowDate() + FILE_PREFIX;
    }

    public static String getNowDate() {
        return S_DATE_FORMAT.get().format(new Date());
    }

    public static String getTargetLogFileDirPath() {
        return STORAGE_PATH + File.separator + LOG_DIR_NAME;
    }

    public static boolean copyFile(String oldPath, String newPath) {

        try {
            if (!isFileExist(newPath)) {
                File newFile = new File(newPath);
                createDir(newFile.getParent());
                newFile.createNewFile();
            }
            File oldFile = new File(oldPath);
            if (!oldFile.exists()) {
                return false;
            } else if (!oldFile.isFile()) {
                return false;
            } else if (!oldFile.canRead()) {
                return false;
            }
            FileInputStream fileInputStream = new FileInputStream(oldPath);
            FileOutputStream fileOutputStream = new FileOutputStream(newPath);
            byte[] buffer = new byte[1024];
            int byteRead;
            while (-1 != (byteRead = fileInputStream.read(buffer))) {
                fileOutputStream.write(buffer, 0, byteRead);
            }
            fileInputStream.close();
            fileOutputStream.flush();
            fileOutputStream.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @param count delete log file 'count' days ago
     */
    private static void deleteOldFile(int count, String path) {
        File dir = new File(path);
        if (!dir.exists() || !dir.isDirectory() || dir.listFiles() == null) {
            return;
        }
        for (File file : dir.listFiles()) {
            if (!file.isFile()) {
                continue;
            }
            String fileName = getFileNameWithoutExtension(file.getAbsolutePath());
            fileName = fileName.replace(FILE_LOG_FIRST_NAME, "");
            try {
                Date fileDate = S_DATE_FORMAT.get().parse(fileName);
                long diff = System.currentTimeMillis() - fileDate.getTime();
                long diffDays = diff / (24L * 60 * 60 * 1000);
                if (diffDays >= count) {
                    file.delete(); // 删除文件
                }
            } catch (ParseException e) {
                e.printStackTrace();
                file.delete(); // 删除文件
            }
        }
    }

    /**
     * save ScreenShot file
     */
    public static void saveScreenShot(String name) {
        try {
            String state = Environment.getExternalStorageState();
            if (Environment.MEDIA_MOUNTED.equals(state)) {
                String storagePath = Environment.getExternalStorageDirectory().getAbsolutePath() +
                        File.separator + BuildConfig.APPLICATION_ID;
                createDir(storagePath);
                createDir(IMG_DIR_PATH);
                deleteDirFile(IMG_DIR_PATH);
                ActivityHelper.screenShot(IMG_DIR_PATH, name);
            }
        } catch (Exception e) {
            LogUtil.log("saveScreenShot Exception" + e.getMessage());
            e.printStackTrace();
        }
    }

    private static void quietClose(Closeable closeable) {
        if (null != closeable) {
            try {
                closeable.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static String stringNowTime() {
        @SuppressLint("SimpleDateFormat")
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return dateFormat.format(new Date());
    }

    /**
     * @param path target dir path
     * @return boolean
     */
    //创建sd上文件夹
    private static boolean createDir(String path) {
        File dirFile = new File(path);
        return dirFile.exists() || dirFile.mkdirs();
    }

    /**
     * @param path     target dir path
     * @param fileName target file name
     * @return boolean
     */
    private static boolean delFile(String path, String fileName) {
        File file = new File(path, fileName);
        return file.isFile() && file.exists() && file.delete();
    }

    /**
     * @param path target dir path
     * @return boolean
     */
    public static boolean delFile(String path) {
        LogUtil.log("delFile path: " + path);
        File file = new File(path);
        return file.isFile() && file.exists() && file.delete();
    }

    public static void deleteDirFile(String path) {
        File dir = new File(path);
        if (!dir.exists() || !dir.isDirectory())
            return;

        for (File file : dir.listFiles()) {
            if (file.isFile())
                file.delete(); // 删除�?��文件
            else if (file.isDirectory())
                deleteDirOrFile(path); // 递规的方式删除文件夹
        }
    }

    public static boolean isFileExist(String strFilePath) {
        File file = new File(strFilePath);
        return file.isFile() && file.exists();
    }

    public static void deleteDirOrFile(String path) {
        LogUtil.log("deleteDirOrFile path: " + path);
        File dir = new File(path);
        if (!dir.exists() || !dir.isDirectory())
            return;
        for (File file : dir.listFiles()) {
            if (file.isFile())
                file.delete(); // 删除�?��文件
            else if (file.isDirectory())
                deleteDirOrFile(path); // 递规的方式删除文件夹
        }
        dir.delete();// 删除目录本身
    }

    public static String ReadTxtFile(String strFilePath) {
        String content = ""; //文件内容字符串
        try {
            FileReader fr = new FileReader(strFilePath);
            BufferedReader r = new BufferedReader(fr);
            content = r.readLine();
        } catch (FileNotFoundException e) {
            LogUtil.log("ReadTxtFile The File doesn't not exist.");
        } catch (IOException e) {
            LogUtil.log("ReadTxtFile : " + e.getMessage());
        }
        return content;
    }

    public static String getFileNameWithoutExtension(String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            return filePath;
        }

        int extensionPos = filePath.lastIndexOf(FILE_EXTENSION_SEPARATOR);
        int filePos = filePath.lastIndexOf(File.separator);
        if (filePos == -1) {
            return (extensionPos == -1 ? filePath : filePath.substring(0, extensionPos));
        }
        if (extensionPos == -1) {
            return filePath.substring(filePos + 1);
        }
        return (filePos < extensionPos ? filePath.substring(filePos + 1, extensionPos) : filePath.substring(filePos + 1));
    }
}
